<template>
  <el-dialog
      v-model="internalModelValue"
      @close="handleClose"
      title="分配角色"
      width="30%"
  >
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-select
            v-model="selectedList"
            multiple
            placeholder="Select"
            style="width: 240px"
        >
          <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<script setup>
import {ref, watch} from 'vue'
import axiosUtil from "@/util/axios";
import {ElMessage} from "element-plus";

const props = defineProps({
  modelValue: Boolean,
  userId: Number
})
const emit = defineEmits(['update:modelValue', 'initTableData'])

const internalModelValue = ref(props.modelValue) // 内部管理的弹框状态
// 已选中的角色list
const selectedList = ref([])
const roleList = ref([])

const onSubmit = async () => {
  try {
    let result = await axiosUtil.postJson('/user/binging-role/', {"id": props.userId, "roleIds": selectedList.value})
    if (result.status === 200) {
      ElMessage.success('绑定成功')
      emit('update:modelValue', false) // 关闭弹框
      emit('initTableData') // 通知父组件刷新列表
    }else {
      ElMessage.error('绑定失败')
    }
  }catch (e) {
    ElMessage.error('绑定失败')
  }
}

// 获取角色列表
const queryRoleData = async () => {
  try {
    let result = await axiosUtil.get('/role/list/')
    if (result.status === 200) {
      roleList.value = result.data
    }else {
      ElMessage.error('提交失败')
    }
  }catch (e) {
    ElMessage.error('提交失败')
  }
}

// 获取用户角色列表
const queryUserRoleList = async () => {
  try {
    let result = await axiosUtil.post('/user/find-user-role/', {"userId": props.userId})
    if (result.status === 200) {
      selectedList.value = result.data.map(item => item.id);
    }else {
      ElMessage.error('提交失败')
    }
  }catch (e) {
    ElMessage.error('提交失败')
  }
}

// 关闭
const handleClose = () => {
  emit('update:modelValue', false) // 通知父组件关闭弹框
  selectedList.value = [] // 清空值
};

watch(() => props.modelValue, (newVal) => {
  internalModelValue.value = newVal
  if (newVal) {
    queryRoleData()
    queryUserRoleList()
  }
})
</script>

<style scoped>

</style>
